import React from 'react';
import classNames from 'classnames';
import Icon from '../Icon';
import Time from '../Time/Time';
import Dom from '../utils/Dom';
import {dateFormat, alignPostion} from '../utils/Utils';

import './TimeRange.less';

class TimeRange extends React.Component {
    static displayName = 'TimeRange';

    static defaultProps = {
        format: 'hh:mm:ss',
        align: 'bottomLeft',
        sep: '-'
    };

    state = {
        open: false,
        optionStyle: {}
    }

    onShowHide = (e) => {
        const {disabled, align} = this.props;
        const ele = e.target || e.srcElement;
        // click clear icon
        if (ele.tagName === 'I' && ele.className.indexOf('cm-time-picker-clear') !== -1) {
            return;
        }
        if (disabled) {
            return;
        }
        const open = this.state.open;
        this._isMounted && this.setState({
            open: !open
        }, () => {
            const optionStyle = alignPostion(align, this.rel, this.dropdown);
            this.setState({
                optionStyle
            });
        });
    }

    componentDidMount () {
        this._isMounted = true;
        document.addEventListener('click', this.clickAnyWhere.bind(this), false);
    }

    componentWillUnmount () {
        this._isMounted = false;
        document.removeEventListener('click', this.clickAnyWhere);
    }

    clickAnyWhere (e) {
        const ele = e.target || e.srcElement;
        const parent = Dom.closest(ele, '.cm-time-picker');
        if (parent && parent == this.wrap) {
            return ;
        } else {
            this._isMounted && this.setState({
                open: false
            });
        }
    }

    close () {
        this._isMounted && this.setState({
            open: false
        });
    }

    onClear = () => {
        this.props.onChange && this.props.onChange('');
    }

    onChangeStart = (current) => {
        const {value} = this.props;
        let time = value;
        if (!time || (time instanceof Array && !time.length)) {
            time = [new Date(), new Date()];
            time[0].setHours(0);time[0].setMinutes(0);time[0].setSeconds(0);
            time[1].setHours(0);time[1].setMinutes(0);time[1].setSeconds(0);
        } else {
            time = [new Date(value[0]), new Date(value[1])];
        }
        time[0].setHours(current[0]);
        time[0].setMinutes(current[1]);
        time[0].setSeconds(current[2]);
        this.sortTime(time);
        this.props.onChange && this.props.onChange(time);
    }

    onChangeEnd = (current) => {
        const {value} = this.props;
        let time = value;
        if (!time || (time instanceof Array && !time.length)) {
            time = [new Date(), new Date()];
            time[0].setHours(0);time[0].setMinutes(0);time[0].setSeconds(0);
            time[1].setHours(0);time[1].setMinutes(0);time[1].setSeconds(0);
        } else {
            time = [new Date(value[0]), new Date(value[1])];
        }
        time[1].setHours(current[0]);
        time[1].setMinutes(current[1]);
        time[1].setSeconds(current[2]);
        
        if (this.isEndBefore(time)) {
            return false;
        }
        this.sortTime(time);
        this.props.onChange && this.props.onChange(time);
    }

    isEndBefore (time) {
        if (time[0].getHours() > time[1].getHours()) {
            return true;
        } else {
            if (time[0].getHours() === time[1].getHours()
            && time[0].getMinutes() > time[1].getMinutes()) {
                return true;
            } else {
                if (time[0].getHours() === time[1].getHours()
                && time[0].getMinutes() === time[1].getMinutes()
                && time[0].getSeconds() > time[1].getSeconds()) {
                    return true;
                }
            }
        }
        return false;
    }

    sortTime (time) {
        if (time[0].getHours() > time[1].getHours()) {
            time[1].setHours(time[0].getHours());
        } else {
            if (time[0].getMinutes() > time[1].getMinutes()) {
                time[1].setMinutes(time[0].getMinutes());
            } else {
                if (time[0].getSeconds() > time[1].getSeconds()) {
                    time[1].setSeconds(time[0].getSeconds());
                }
            }
        }
    }

    render () {
        const {value, format, className, style, disabled, align, theme, size, clearable, disabledTime, sep} = this.props;
        let time = value;
        if (!time || (time instanceof Array && !time.length)) {
            time = [new Date(), new Date()];
            time[0].setHours(0);time[0].setMinutes(0);time[0].setSeconds(0);
            time[1].setHours(0);time[1].setMinutes(0);time[1].setSeconds(0);
        }
        const current1 = [time[0].getHours(), time[0].getMinutes(), time[0].getSeconds()];
        const current2 = [time[1].getHours(), time[1].getMinutes(), time[1].getSeconds()];
        const clazzName = classNames('cm-time-range-picker', 'cm-time-picker', className, {
            'cm-time-picker-disabled': disabled,
            [`cm-time-picker-${align}`]: align,
            [`cm-time-picker-${theme}`]: theme,
            [`cm-time-picker-${size}`]: size,
            'cm-time-picker-clearable': !disabled && clearable && value !== '',
            'cm-time-picker-open': this.state.open
        });
        const text = (!value || (value instanceof Array && !value.length)) ? '' : dateFormat(format, time[0]) + sep + dateFormat(format, time[1]);
        return <div className={clazzName} style={style} ref={f => this.wrap = f}>
            <div className='cm-time-picker-value' onClick={this.onShowHide} tabIndex='0' ref={f => this.rel = f}>
                <input type='hidden' name={name} value={value} />
                <div className='cm-time-picker-text'>{text}</div>
                <Icon name='clock' className='cm-time-picker-cert'/>
                {
                    clearable
                        ? <Icon name='x-circle' className='cm-time-picker-clear' onClick={this.onClear}/>
                        : null
                }
            </div>
            <div className='cm-time-picker-wrap' ref={f => this.dropdown = f} style={this.state.optionStyle}>
                <div className='cm-time-range-item'>
                    <div className='cm-time-range-title'>开始时间</div>
                    <div className='cm-time-range-body'>
                        <Time format={format} current={current1} onChange={this.onChangeStart} disabledTime={disabledTime} />
                    </div>
                </div>
                <div className='cm-time-range-item'>
                    <div className='cm-time-range-title'>结束时间</div>
                    <div className='cm-time-range-body'>
                        <Time format={format} current={current2} onChange={this.onChangeEnd} disabledTime={disabledTime} />
                    </div>
                </div>
            </div>
        </div>;
    }
}

export default TimeRange;
